﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;

namespace NMemcached.Client.Configuration
{
    internal class TransportConverter : ConfigurationConverterBase
    {
        public TransportConverter()
            : base()
        {
        }

        public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type type)
        {
            bool canConvert = base.CanConvertFrom(ctx, type);

            if (type.IsAssignableFrom(typeof(string)))
            {
                canConvert = true;
            }

            return canConvert;
        }

        public override bool CanConvertTo(ITypeDescriptorContext ctx, Type type)
        {
            bool canConvert = base.CanConvertTo(ctx, type);

            if (type.IsAssignableFrom(typeof(string)))
            {
                canConvert = true;
            }

            return canConvert;
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            object converted = null;

            if (value.GetType().IsAssignableFrom(typeof(string)))
            {
                converted = (TransportType)Enum.Parse(typeof(TransportType), value.ToString(), true);
            }
            else
            {
                converted = base.ConvertFrom(context, culture, value);
            }

            return converted;
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            object converted = null;

            if (destinationType.IsAssignableFrom(typeof(string)) && value.GetType().IsAssignableFrom(typeof(TransportType)))
            {
                converted = ((TransportType)value).ToString().ToLower();
            }
            else
            {
                converted = base.ConvertTo(context, culture, value, destinationType);
            }

            return converted;
        }
    }
}
